import { useEffect, FC, ReactNode, useState, useRef } from 'react';
import { View, Text, Image, Button } from '@tarojs/components'
import { AtButton } from 'taro-ui'
import './index.less';
import "taro-ui/dist/style/components/form.scss";
import Search from '@resource/tabImg/search.svg'
import Edit from '@resource/tabImg/toEdit.svg'
import Taro from '@tarojs/taro';
import { AtModal, AtModalHeader, AtModalContent, AtModalAction, AtCurtain, AtMessage } from "taro-ui"
import { querySingleAccount, queryBatchAccount } from '@api/account.ts'
import { validateData } from '@untils/functions'
import NoWin from '@resource/tabImg/noWin.svg'
import Youarewin from '@resource/tabImg/youarewin.svg'

// 定义 Props 接口
interface Props {
  children?: ReactNode;
}
enum QueryType {
  single = 'single',
  batch = 'batch'
}
type QueryTypeUnion = keyof typeof QueryType;

const singleData = [
  { last_name: '李卫', id_number_pre: '513', id_number_suf: '325X', phone_pre: '130', phone_suf: 8325 }
]
const batchData = [
  { last_name: '李卫', id_number_pre: '513', id_number_suf: '325X', phone_pre: '130', phone_suf: 8325 },
  { last_name: '李卫', id_number_pre: '513', id_number_suf: '325X', phone_pre: '130', phone_suf: 8325 },
  { last_name: '李卫', id_number_pre: '513', id_number_suf: '325X', phone_pre: '130', phone_suf: 8325 },
]
const Index: FC<Props> = () => {
  const { single, batch } = QueryType
  const [queryType, setQueryType] = useState<QueryTypeUnion>(single)
  const [nodataWarnVisible, setNodataWarnVisible] = useState(false)
  const [singleWinnerList, setSingleWinnerList] = useState([])
  const [batchWinnerList, setBatchWinnerList] = useState([])
  const [winnerStateVisible, setWinnerStateVisible] = useState(false)
  const isWinRef = useRef<boolean>()
  useEffect(() => {
    // 任何你需要在组件挂载时执行的副作用

  }, []);

  const singleQuery = async () => {
    try {
      const result = await querySingleAccount()
      if (result.code === 200) {
        const data = result.data
        if (data.length) {
          setSingleWinnerList(data)
          isWinRef.current = true
        } else {
          isWinRef.current = false
        }
        setWinnerStateVisible(true)
      } else {
        Taro.atMessage({
          'message': '查询出错，请重试',
          'type': 'error',
        })
      }
    } catch (error) {
      console.error('查询失败，请重试',);
    }
  };

  const batchQuery = async () => {
    try {
      const result = await queryBatchAccount()
      if (result.code === 200) {
        const data = result.data
        if (data.length) {
          setBatchWinnerList(data)
          isWinRef.current = true
        } else {
          isWinRef.current = false
        }
        setWinnerStateVisible(true)
      } else {
        Taro.atMessage({
          'message': '查询出错，请重试',
          'type': 'error',
        })
      }
    } catch (error) {
      console.error('查询失败，请重试',);
    }
  };


  const switchQueryType = (type: QueryTypeUnion) => {
    setQueryType(type)
  }

  const goToEditAccountInfo = () => {
    Taro.navigateTo({
      url: `/pages/accountManage/index?type=${queryType}`,
    })
  }

  const goToSearch = () => {
    if (queryType === single) {
      const singleAccountInfo = Taro.getStorageSync('singleAccountInfo') || {}
      const { isValid } = validateData(singleAccountInfo)
      if (!isValid) {
        setNodataWarnVisible(true)
        return
      }
      singleQuery()
    }
    if (queryType === batch) {
      const batchAccountInfo = Taro.getStorageSync('batchAccountInfo') || []
      if (!batchAccountInfo.length) {
        setNodataWarnVisible(true)
        return
      }
      batchQuery()
    }
  }

  const gotoSaveInfo = () => {
    setNodataWarnVisible(false)
    Taro.navigateTo({
      url: `/pages/accountManage/index?type=${queryType}`,
    })
  }

  const renderSingleWinnerList = () => {
    return singleWinnerList.map((item) => {
      const { last_name, id_number_pre, id_number_suf, phone_pre, phone_suf } = item
      return <View className='singleContent'>
        <Text className='name'>{last_name || '马云'}</Text>
        <Text className='idNumber'>{id_number_pre || 'xxx'}-{id_number_suf || 'xxxx'}</Text>
        <Text className='phoneNumber'>{phone_pre || 'xxx'}-{phone_suf || 'xxxx'}</Text>
      </View>
    })
  }

  const renderBatchWinnerList = () => {
    return batchWinnerList.map((item) => {
      const { last_name, id_number_pre, id_number_suf, phone_pre, phone_suf } = item
      return <View className='singleContent'>
        <Text className='name'>{last_name || '马云'}</Text>
        <Text className='idNumber'>{id_number_pre || 'xxx'}-{id_number_suf || 'xxxx'}</Text>
        <Text className='phoneNumber'>{phone_pre || 'xxx'}-{phone_suf || 'xxxx'}</Text>
      </View>
    })
  }

  const onCloseWinner = () => {
    setWinnerStateVisible(false)
    isWinRef.current = false
  }
  return (
    <View className='bigBox'>
      <AtMessage />
      {/* <AccountManage /> */}
      <View className='winnerQuery'>
        <View className='queryType'>
          <Text className='header'>
            <Text style={{ marginRight: '52rpx' }} className={`${queryType === single ? 'checked' : 'single'}`} onClick={() => switchQueryType(single)}>单个查询</Text>
            <Text className={`${queryType === batch ? 'checked' : 'batch'}`} onClick={() => switchQueryType(batch)}>批量查询</Text>
          </Text>
        </View>
        <View className='otherAction'>
          <View className='btnBox btn1' onClick={goToSearch}>
            <AtButton className='desc'>{queryType === single ? '单号查一下' : '多号查一下'}
            </AtButton>
            <Image className='toSearch' src={Search} mode='aspectFill' />
          </View>
          <View className='btnBox btn2' onClick={goToEditAccountInfo}>
            <AtButton className='desc descTwo'>编辑账号信息</AtButton>
            <Image className='toEdit' src={Edit} mode='aspectFill' />
          </View>
        </View>
        {
          queryType === single && <>
            {singleWinnerList.length ? <View className='winnerTitle'>恭喜下面的各位老板中签：</View> : null}
            <View className='result'>
              {!singleWinnerList.length ? <Text className='result-desc'>暂无中签信息</Text> :
                <View className='single'>
                  <Text className='name'>姓名</Text>
                  <Text className='idNumber'>身份证</Text>
                  <Text className='phoneNumber'>手机号码</Text>
                </View>
              }
              {renderSingleWinnerList()}
            </View>
          </>
        }
        {
          queryType === batch && <>
            {batchWinnerList.length ? <View className='winnerTitle'>恭喜下面的各位：</View> : null}
            <View className='result'>
              {!batchWinnerList.length ? <Text className='result-desc'>暂无中签信息</Text> :
                <View className='single'>
                  <Text className='name'>姓名</Text>
                  <Text className='idNumber'>身份证</Text>
                  <Text className='phoneNumber'>手机号码</Text>
                </View>
              }
              {renderBatchWinnerList()}
            </View>
          </>
        }
        <View className='introduce'>
          <Text><Text className='insideText'>提示：</Text> 不论是单一账号还是多账号，我们都将根据三要素为您提供精准查询</Text>
        </View>
      </View>
      <AtModal isOpened={nodataWarnVisible} className='transformModal' onClose={() => setNodataWarnVisible(false)}>
        <AtModalHeader>温馨提示</AtModalHeader>
        <AtModalContent>
          您还没有添加{queryType === single ? '单个查询' : '批量查询'}的账号信息，请点击下方按钮去添加吧！
        </AtModalContent>
        <AtModalAction>
          <Button className='sureDo' onClick={() => gotoSaveInfo()}>添加账号信息</Button>
        </AtModalAction>
      </AtModal>
      <AtCurtain
        isOpened={winnerStateVisible}
        onClose={onCloseWinner}
        className='winner-result'
      >
        <View className={isWinRef.current ? 'youwin' : 'nowin'}>
          <Image
            className='way'
            src={isWinRef.current ? Youarewin : NoWin}
            mode='aspectFit'
          />
        </View>

      </AtCurtain>
    </View >
  );
};

export default Index;
